package com.fanghuyun.iswaf.service;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

import com.fanghuyun.iswaf.common.Constants;
import com.fanghuyun.iswaf.common.JspInfo;
import com.fanghuyun.iswaf.common.SysConfig;

public class AppInfo {
	
	private static Logger logger = Logger.getLogger("iswaf.client");

	public static Map<String,Object> info(JSONObject json,HttpServletRequest request){
		Map<String,Object> result = new HashMap<String, Object>();
		JspInfo info = new JspInfo();
		try {
			SysConfig sc = new SysConfig();
			if("info".equals(json.get("type"))){
				result.put("out",info.getJspInfo(request));
			}else{
				if(validate()){
					result.put("writeable", new File(sc.getServerPath()).canWrite());
					result.put("version", Constants.SYS_CONFIG_VERSION);
				}
			}
		} catch (Exception e) {
			result.put("info", false);
			logger.info("validate failed.");
		}
		return result;
	}

	public static boolean validate(){
		try {
			SysConfig sc = new SysConfig();
			File path = new File(sc.getServerPath());
			if(path.canRead()&&path.canWrite()){
				FileUtils.copyFileToDirectory(new File(System.getProperty("user.dir").replaceAll("\\\\", "/")+"/SysConfig.properties"), new File(sc.getIsWafConfDirectory()));
			}
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			logger.info("validate failed.",e);
			return false;
		}
	}

}
